package com.shop.controller;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.shop.pojo.Auctionuser;
import com.shop.service.UserService;

@Controller
public class LoginController {
	@Autowired
	private UserService userService;

//	//跳转普通用户登录页面
//	@RequestMapping(value = "/login")
//	public String login() {
//		return "login";
//	}
//	
//	//跳转管理员登录页面
//	@RequestMapping("/adminLogin")
//	public String adminLogin() {
//		return "adminLogin";
//	}
//	
	//RestFul
	@RequestMapping("/{page}")
	public String page(@PathVariable String page) {
		return page;
	}
	
	//登录判断,因为要带错误信息回登录页面，所以不能用重定向
	@RequestMapping("/CheckLogin")
	public String CheckLogin(String username,String password,
			String verifycode,@RequestParam("page")String page,HttpSession session,Model m) {
		System.out.println(page);
		//先判断验证码
		String vrifyCode = (String) session.getAttribute("vrifyCode");
		if(!vrifyCode.equalsIgnoreCase(verifycode)) {
			m.addAttribute("errorMsg", "验证码不正确");
			if(page.equals("adminLogin")) {
				//后台登录页面
				return page;
			}
			//前台登录页面
			return "login";
		}
		
		//判断用户名和密码
		List<Auctionuser> list = userService.selectByExample(username, password);
		if(list.size()>0&&list!=null) {
			Auctionuser user = list.get(0);
			//登录成功，将用户信息存进session
			session.setAttribute("user", user);
			//重定向跳转查询所有拍卖品，再转发到首页
			return "redirect:findAllAuctions";
		}else {
			m.addAttribute("errorMsg", "账号或密码不正确");
			if(page.equals("adminLogin")) {
				//后台登录页面
				return page;
			}
			return "login";
		}
		
	}
	
	//跳转注册页面
	@RequestMapping("/toregister")
	public String toregister() {
		
		return "register";
	}
	
	//注册,默认注册为普通用户
	@RequestMapping("/register")
	public String register(Auctionuser user) {
		//user.setUserisadmin(0);
		userService.register(user);
		//注册完成，重定向到登录方法从而跳转登录页面
		return "redirect:login";
	}
	
	//退出登录
	@RequestMapping("/logout")
	public String logout(HttpSession session) {
		Auctionuser user = (Auctionuser)session.getAttribute("user");
		session.invalidate();
		if(user.getUserisadmin()==1) {
			return "redirect:adminLogin";
		}
		return "redirect:login";
	}

}
